package com.ls.lserp.modules.trade.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.service.CrudService;
import com.ls.lserp.common.utils.CollectionsUtils;
import com.ls.lserp.common.utils.DateUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.excel.template.ExcelTemplate;
import com.ls.lserp.modules.order.entity.MaterialPurchase;
import com.ls.lserp.modules.order.entity.OrderMateriel;
import com.ls.lserp.modules.sys.utils.DictUtils;
import com.ls.lserp.modules.trade.dao.EnchaseDao;
import com.ls.lserp.modules.trade.entity.CartonInfo;
import com.ls.lserp.modules.trade.entity.Enchase;

/**
 * @ClassName: EnchaseService
 * @Description: 装箱单
 * 
 * @author
 * @date 2017年3月24日 下午18:40:40
 *
 */

@Service
@Transactional(readOnly = true)
public class EnchaseService extends CrudService<EnchaseDao, Enchase> {

	@Autowired
	private EnchaseDao enchaseDao;

	public static final String PACKAGE_NO = "PACKAGE";

	/**
	 * @Title: findList @Description: 查询 @param @param page @param @param
	 * enchase @param @return @return Page<HandBook> @throws
	 */
	public Page<Enchase> findList(Page<Enchase> page, Enchase enchase) {

		// tab页分，检索条件设定(0:全部,1:待装箱,2:已装箱,3:已删除)
		int tabFlg = enchase.getTabPageStatus();
		enchase.setEnchaseDelFlg(Enchase.DEL_FLAG_NORMAL);
		if (1 == tabFlg) {
			enchase.setPackageStatus(ResourcesUtil.getConfig("package_status_unpacked"));
		} else if (2 == tabFlg) {
			enchase.setPackageStatus(ResourcesUtil.getConfig("package_status_packed"));
		} else if (3 == tabFlg) {
			enchase.setEnchaseDelFlg(Enchase.DEL_FLAG_DELETE);
			enchase.setPackageStatus("");
		} else {
			enchase.setPackageStatus("");
		}

		// 设置分页参数
		enchase.setPage(page);

		List<Enchase> resultList = enchaseDao.findList(enchase);

		// 执行分页查询
		page.setList(resultList);

		return page;
	}

	/**
	 * @Title: findCartonInfoList @Description: 查询纸箱 @param @param
	 * cartonInfo @param @return @return List<CartonInfo> @throws
	 */

	public List<CartonInfo> findCartonInfoList(CartonInfo cartonInfo) {

		return enchaseDao.findCartonInfoList(cartonInfo);
	}

	/**
	 * @Title: findIndentList @Description: 查询订单（颜色，尺寸分） @param @param
	 * enchase @param @return @return List<Enchase> @throws
	 */

	public List<Enchase> findIndentList(Long indentId) {
		Enchase pEnchase = new Enchase();
		pEnchase.setIndentId(indentId);
		return enchaseDao.findIndentList(pEnchase);
	}

	/**
	 * @Title: findSizeList @Description: 获得所有尺码一览 @param @param
	 * enchase @param @return @return List<Enchase> @throws
	 */

	public List<Enchase> findSizeList(Long indentId) {
		Enchase pEnchase = new Enchase();
		pEnchase.setIndentId(indentId);
		return enchaseDao.findSizeList(pEnchase);
	}

	/**
	 * @Title: saveDict @Description: 保存基准数据 @param @param dict @return
	 * void @throws
	 */
	@Transactional(readOnly = false)
	public void saveEnchase(Enchase enchase) {

		// 判断新建编辑
		// 若为null 执行插入语句（新建）
		if (enchase.getId() == null) {
			enchase.preInsert();
			enchase.setVersion(1L);

			// 取得手册编号
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String dateNowStr = sdf.format(new Date());
			enchase.setPackageNo(PACKAGE_NO + dateNowStr);
			enchase.setPackageStatus(ResourcesUtil.getConfig("package_status_unpacked"));
			enchase.setContractId(enchase.getIndentList().get(0).getContractId());
			enchase.setIndentId(enchase.getIndentList().get(0).getIndentId());
			enchase.setStyleId(enchase.getIndentList().get(0).getStyleId());
			enchaseDao.insertPackageP(enchase);

			// 编辑
		} else {
			// 更新数据
			enchase.preUpdate();
			enchase.setContractId(enchase.getIndentList().get(0).getContractId());
			enchase.setIndentId(enchase.getIndentList().get(0).getIndentId());
			enchase.setStyleId(enchase.getIndentList().get(0).getStyleId());
			enchaseDao.update(enchase);
			// 删除出口成本数据
			enchaseDao.deletePackageDetails(enchase);
		}

		// 判断list是否为空
		if (!CollectionsUtils.isEmpty(enchase.getPackageDetailsList())) {
			Enchase newDetialsInfo = null;
			long i = 1L;
			// 遍历赋值
			for (Enchase packageDetailInfo : enchase.getPackageDetailsList()) {
				for (Enchase packageDetailAllSizeInfo : packageDetailInfo.getAllSizeList()) {
					if (packageDetailAllSizeInfo.getCartonStyleQuantity() != null
							&& !packageDetailAllSizeInfo.getCartonStyleQuantity().equals("0")) {
						newDetialsInfo = new Enchase();
						newDetialsInfo.preInsert();
						newDetialsInfo.setVersion(1L);
						newDetialsInfo.setId(enchase.getId());
						newDetialsInfo.setCountryCd(packageDetailInfo.getCountryCd());
						newDetialsInfo.setCartonId(packageDetailInfo.getCartonId());
						newDetialsInfo.setCartonNoFrom(packageDetailInfo.getCartonNoFrom());
						newDetialsInfo.setCartonNoTo(packageDetailInfo.getCartonNoTo());
						newDetialsInfo.setCartonPackageStyle(packageDetailInfo.getPackageStyle());
						newDetialsInfo.setCartonStyleQuantity(packageDetailAllSizeInfo.getCartonStyleQuantity());
						newDetialsInfo.setCartonQuantity(packageDetailInfo.getCartonQuantity());
						newDetialsInfo.setCartonColorName(packageDetailInfo.getCartonColorName());
						newDetialsInfo.setCartonSizeGroupCd(enchase.getIndentList().get(0).getStyleSizeGroupCd());
						newDetialsInfo.setCartonSizeCd(packageDetailAllSizeInfo.getCartonSizeCd());
						newDetialsInfo.setCartonNetWeight(packageDetailInfo.getCartonNetWeight());
						BigDecimal packageWeight = (checkBigDecimalNull(packageDetailInfo.getBoxWeight())
								.multiply(checkBigDecimalNull(new BigDecimal(packageDetailInfo.getCartonQuantity()))))
										.setScale(2, BigDecimal.ROUND_HALF_UP);
						newDetialsInfo.setCartonRoughWeight(
								checkBigDecimalNull(packageDetailInfo.getCartonNetWeight()).add(packageWeight));
						newDetialsInfo.setCartonVolume((checkBigDecimalNull(packageDetailInfo.getBoxVolume())
								.multiply(checkBigDecimalNull(new BigDecimal(packageDetailInfo.getCartonQuantity()))))
										.setScale(2, BigDecimal.ROUND_HALF_UP));
						newDetialsInfo.setPackageDetailsSort(i);
						// 执行子项插入语句
						enchaseDao.insertPackageDetailsS(newDetialsInfo);
					}
				}
				i++;
			}
		}
	}

	/**
	 * check BigDecimal
	 * 
	 * @param cost
	 * @return 取不到返回0
	 */
	public BigDecimal checkBigDecimalNull(BigDecimal cost) {
		if (cost == null) {
			return new BigDecimal("0");
		}
		return cost;
	}

	/**
	 * @Title: findPackageDetailsList @Description: 箱单一览 @param @param
	 * enchase @param @return @return List<Enchase> @throws
	 */

	public List<Enchase> findPackageDetailsList(Enchase enchase) {
		return enchaseDao.findPackageDetailsList(enchase);
	}

	/**
	 * @Title: setPackageDetailsList @Description: 箱单明细一览 @param @param
	 * enchase @param @return @return List<Enchase> @throws
	 */

	public List<Enchase> setPackageDetailsList(List<Enchase> packageDetailsList, List<Enchase> allSizeList) {
		// 明细sort
		long preSort = -1;
		// 返回箱单明细list
		List<Enchase> returnEnchaseList = new ArrayList<Enchase>();
		// 新明细信息
		Enchase tempEnchse = null;

		// sort相同的数据合并成一条数据
		for (Enchase forEnchase : packageDetailsList) {
			if (preSort != forEnchase.getPackageDetailsSort()) {
				tempEnchse = new Enchase();
				tempEnchse.setAllSizeList(getNewSizeList(allSizeList));
				// 国家cd
				tempEnchse.setCountryCd(forEnchase.getCountryCd());
				// 纸箱id
				tempEnchse.setCartonId(forEnchase.getCartonId());
				// 纸箱名
				tempEnchse.setCartonName(forEnchase.getCartonName());
				// 箱号from
				tempEnchse.setCartonNoFrom(forEnchase.getCartonNoFrom());
				// 箱号to
				tempEnchse.setCartonNoTo(forEnchase.getCartonNoTo());
				// 装箱类别
				tempEnchse.setPackageStyle(forEnchase.getPackageStyle());
				// 箱数
				tempEnchse.setCartonQuantity(forEnchase.getCartonQuantity());
				// 颜色
				tempEnchse.setCartonColorName(forEnchase.getCartonColorName());
				// 净重
				tempEnchse.setCartonNetWeight(forEnchase.getCartonNetWeight());
				// 客户合同号
				tempEnchse.setCustomerContractNo(forEnchase.getCustomerContractNo());
				// 客户款号
				tempEnchse.setStyleCustomerNo(forEnchase.getStyleCustomerNo());
				// 纸箱体积
				tempEnchse.setBoxVolume(forEnchase.getBoxVolume());
				// 纸箱重量
				tempEnchse.setBoxWeight(forEnchase.getBoxWeight());
				// 每箱件
				tempEnchse.setSingleCarton(forEnchase.getSingleCarton());
				returnEnchaseList.add(tempEnchse);
				preSort = forEnchase.getPackageDetailsSort();
			}
			// 设定尺码所对应的衣服件数
			if (StringUtils.isNotEmpty(forEnchase.getCartonSizeCd())) {
				for (Enchase forSize : tempEnchse.getAllSizeList()) {
					if (forSize.getCartonSizeCd().equals(forEnchase.getCartonSizeCd())) {
						forSize.setCartonStyleQuantity(forEnchase.getCartonStyleQuantity());
					}
				}
			}
		}

		List<String> repeatValue = new ArrayList<String>();
		String strFromTo = "";
		long countMoreCarton = 0L;
		// 设定总件数和设定箱号重复标记
		for (Enchase ec : returnEnchaseList) {
			strFromTo = ec.getCartonNoFrom() + "," + ec.getCartonNoTo();
			// 判断箱号是否相同
			if (repeatValue.contains(strFromTo)) {
				ec.setHasCartonFromTo("1");
			} else {
				ec.setHasCartonFromTo("0");
				repeatValue.add(strFromTo);
			}

			// 总件数
			countMoreCarton = ec.getCartonQuantity() * ec.getSingleCarton();
			ec.setMoreCarton(countMoreCarton);
		}

		return returnEnchaseList;
	}

	/**
	 * @Title: getNewSizeList @Description: 新建尺码list @param @param
	 * enchase @param @return @return List<Enchase> @throws
	 */
	public List<Enchase> getNewSizeList(List<Enchase> allSizeList) {
		List<Enchase> pEnchaseList = new ArrayList<Enchase>();
		Enchase sizeInfo = null;
		int allSizeListSize = 0;
		if (!CollectionsUtils.isEmpty(allSizeList)) {
			allSizeListSize = allSizeList.size();
		}

		// 箱单明细的每箱尺寸搭配只显示8个
		for (int i = 0; i < 8; i++) {
			sizeInfo = new Enchase();
			sizeInfo.setSizeName("");
			sizeInfo.setCartonSizeCd("");
			if (i < allSizeListSize) {
				sizeInfo.setSizeName(allSizeList.get(i).getSizeName());
				sizeInfo.setCartonSizeCd(allSizeList.get(i).getCartonSizeCd());
			}
			pEnchaseList.add(sizeInfo);
		}
		return pEnchaseList;
	}

	/**
	 * @Title: findShowIndentList @Description: 设定款式信息的待装箱数 @param @param
	 * enchase @param @return @return List<Enchase> @throws
	 */

	public List<Enchase> findShowIndentList(List<Enchase> packageDetailsList, List<Enchase> indentList) {
		long waitNum = 0L;
		long styleQuantity = 0L;
		for (Enchase e : indentList) {
			for (Enchase pdl : packageDetailsList) {
				if (e.getCartonColorName().equals(pdl.getCartonColorName())) {
					for (Enchase asl : pdl.getAllSizeList()) {
						if (asl.getCartonSizeCd().equals(e.getCartonSizeCd())) {
							if (asl.getCartonStyleQuantity() == null) {
								styleQuantity = 0L;
							} else {
								styleQuantity = asl.getCartonStyleQuantity().longValue();
							}
							waitNum = waitNum + (styleQuantity * pdl.getCartonQuantity());
						}
					}
				}
			}
			e.setUnPackNumber(e.getIndentNumber() - waitNum);
			waitNum = 0L;
		}
		return indentList;
	}

	/**
	 * @Title: findShowCartonInfoList @Description: 设定纸箱信息 @param @param
	 * enchase @param @return @return List<Enchase> @throws
	 */

	public List<CartonInfo> findShowCartonInfoList(List<Enchase> packageDetailsList) {
		String commaCartonId = "";
		List<String> cartonIdList = new ArrayList<String>();
		long count = 0L;

		// 获取纸箱id
		for (Enchase e : packageDetailsList) {
			if (e.getCartonId() != null) {
				if (!cartonIdList.contains(String.valueOf(e.getCartonId().longValue()))) {
					cartonIdList.add(String.valueOf(e.getCartonId().longValue()));
				}
			}
		}

		// 查询纸箱信息
		List<CartonInfo> returnCartonInfoList = new ArrayList<CartonInfo>();
		if (!CollectionsUtils.isEmpty(cartonIdList)) {
			commaCartonId = CollectionsUtils.convertToString(cartonIdList, ",");

			CartonInfo ci = new CartonInfo();
			ci.setCommaCartonId(commaCartonId);

			returnCartonInfoList = enchaseDao.findCartonInfoList(ci);
		}

		// 计算总箱数
		for (CartonInfo forCi : returnCartonInfoList) {
			for (Enchase pdl : packageDetailsList) {
				if (pdl.getHasCartonFromTo().equals("0") && forCi.getId().equals(pdl.getCartonId())) {
					count += pdl.getCartonQuantity();
				}
			}
			forCi.setCartonNumber(count);
			count = 0L;
		}
		return returnCartonInfoList;
	}

	/**
	 * @Title: deleteEnchase @Description: 删除箱单(逻辑删除) @param @param
	 * enchase @return void @throws
	 */

	@Transactional(readOnly = false)
	public void deleteEnchase(Enchase enchase) {
		// 执行逻辑删除
		enchaseDao.delete(enchase);
	}

	/**
	 * @Title: findColorList @Description: 设定颜色下拉 @param @param
	 * enchase @param @return @return List<String> @throws
	 */

	public List<String> findColorList(List<Enchase> indentList) {
		List<String> colorList = new ArrayList<String>();
		for (Enchase e : indentList) {
			if (StringUtils.isNotEmpty(e.getCartonColorName())) {
				if (!colorList.contains(e.getCartonColorName())) {
					colorList.add(e.getCartonColorName());
				}
			}
		}
		return colorList;
	}
	
	/**
     * 导出大货箱单信息
     *
     * @throws IOException
     */
    public ExcelTemplate exportBigOrderEnchase(Enchase enchase , String tempFilePath) throws IOException {
    	
    	// 所有尺码一览
    	List<Enchase> resultSizeList = findSizeList(enchase.getIndentId());
    	enchase.setAllSizeList(resultSizeList);
    	// 箱单明细一览取得
    	List<Enchase> resultPackageDetailsList = findPackageDetailsList(enchase);
    	enchase.setPackageDetailsList(setPackageDetailsList(resultPackageDetailsList, resultSizeList));
        // 返回值
        ExcelTemplate handle = new ExcelTemplate();
        // 输出大货箱单基本信息
        printEnchaseBaseInfoTemp(tempFilePath, enchase.getPackageDetailsList(), handle);
        // 输出大货箱单尺码名称信息
        printEnchaseFitNameTemp(tempFilePath, enchase.getAllSizeList(), handle);
        // 输出大货箱单尺码数量信息
        printEnchaseFitQuantityTemp(tempFilePath, enchase.getPackageDetailsList(), handle);
        
        return handle;

    }
    /**
     * 
     * @param tempFilePath
     * @param packageDetailsList
     * @param handle
     * @throws IOException
     */
    private void printEnchaseFitQuantityTemp(String tempFilePath, List<Enchase> packageDetailsList, ExcelTemplate handle) throws IOException {
    	if (packageDetailsList != null && packageDetailsList.size() > 0) {
    		Enchase tempObj;
    		// 变量声明
    		List<String> dataCellDeclare = new ArrayList<String>();
    		// 变量值集合
    		List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
    		dataCellDeclare.add("sizeQuantity");
			for (int i = 0; i < packageDetailsList.size(); i++) {
				tempObj = packageDetailsList.get(i);
		        //尺码数量
		        // 结果
		        Map<String, Object> map;
		        // 临时接收变量
		        Enchase tempBean;
		        if (tempObj.getAllSizeList() != null && tempObj.getAllSizeList().size() > 0) {
		        	for (int j = 0; j < tempObj.getAllSizeList().size(); j++) {
		        		if (tempObj.getAllSizeList().get(j) != null) {
		        			map = new HashMap<String, Object>();
		        			tempBean = tempObj.getAllSizeList().get(j);
		        			//尺码数量
		        			map.put("sizeQuantity", tempBean.getCartonStyleQuantity());
		        			dataList.add(map);
		        		}
		        	}
				}
			}
			// 向excel表输出
			handle.writeListDataCustom(tempFilePath, dataCellDeclare, dataList, 0 , 8, "false" , 0);
		}
    	
    }
    /**
     * 
     * @param tempFilePath
     * @param allSizeList
     * @param handle
     * @throws IOException
     */
    private void printEnchaseFitNameTemp(String tempFilePath, List<Enchase> allSizeList, ExcelTemplate handle) throws IOException {
        // 变量声明
        List<String> dataCellDeclare = new ArrayList<String>();
        // 变量值集合
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
        //尺码名称
        dataCellDeclare.add("sizeName");
        // 结果
        Map<String, Object> map;
        // 临时接收变量
        Enchase tempBean;
        for (int i = 0; i < allSizeList.size(); i++) {
        	if (allSizeList.get(i) != null) {
        		map = new HashMap<String, Object>();
    			tempBean = allSizeList.get(i);
    			//尺码名称
    			map.put("sizeName", tempBean.getSizeName());
    			dataList.add(map);
        	}
        }
        // 向excel表输出
        handle.writeListDataCustom(tempFilePath, dataCellDeclare, dataList, 0 , 0 , "false" , 0);
    }
    /**
     * 
     * @param tempFilePath
     * @param packageDetailsList
     * @param handle
     * @throws IOException
     */
    private void printEnchaseBaseInfoTemp(String tempFilePath, List<Enchase> packageDetailsList, ExcelTemplate handle) throws IOException {
        // 变量声明
        List<String> dataCellDeclare = new ArrayList<String>();
        // 变量值集合
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
        //No.
        dataCellDeclare.add("No.");
        //合同单号
        dataCellDeclare.add("customerContractNo");
        //款式编号
        dataCellDeclare.add("styleCustomerNo");
        //国别
        dataCellDeclare.add("countryCd");
        //包装类别
        dataCellDeclare.add("packageStyle");
        //颜色
        dataCellDeclare.add("cartonColorName");
        //箱号
        dataCellDeclare.add("cartonNo");
        //箱数
        dataCellDeclare.add("cartonQuantity");
        //箱体名称
        dataCellDeclare.add("cartonName");
        //每箱件数
        dataCellDeclare.add("singleCarton");
        //净重
        dataCellDeclare.add("cartonNetWeight");
        //总件数
        dataCellDeclare.add("moreCarton");
        // 结果
        Map<String, Object> map;
        // 临时接收变量
        Enchase tempBean;
        // 格式化数字
        NumberFormat num = NumberFormat.getInstance();
        for (int i = 0; i < packageDetailsList.size(); i++) {
        	if (packageDetailsList.get(i) != null) {
        		map = new HashMap<String, Object>();
    			tempBean = packageDetailsList.get(i);
    			// No.
    			map.put("No.", i+1);
    			// 合同单号
    			map.put("customerContractNo", tempBean.getCustomerContractNo());
    			// 款式编号
    			map.put("styleCustomerNo", tempBean.getStyleCustomerNo());
    			//国别
    			map.put("countryCd", DictUtils.getDictName(tempBean.getCountryCd()));
    	        //包装类别
    			map.put("packageStyle", DictUtils.getDictName(tempBean.getPackageStyle()));
    	        //颜色
    			map.put("cartonColorName", tempBean.getCartonColorName());
    	        //箱号
    			map.put("cartonNo", tempBean.getCartonNoFrom()+"~"+tempBean.getCartonNoTo());
    	        //箱数
    			map.put("cartonQuantity", tempBean.getCartonQuantity());
    	        //箱体名称
    			map.put("cartonName", tempBean.getCartonName());
    	        //每箱件数
    			map.put("singleCarton", tempBean.getSingleCarton());
    	        //净重
    			map.put("cartonNetWeight", tempBean.getCartonNetWeight());
    	        //总件数
    			map.put("moreCarton", tempBean.getMoreCarton());
    			//map.put("planMaterialLoss", num.format(tempBean.getPlanMaterialLoss().doubleValue()));
    			dataList.add(map);
        	}
        }
        // 向excel表输出
        handle.writeListData(tempFilePath, dataCellDeclare, dataList, 0);
    }
}
